package cn.itcast.tanhua.mytanhuaserver.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.itcast.tanhua.mytanhuadubbointerface.api.QuanziApi;
import cn.itcast.tanhua.mytanhuadubbointerface.api.VideoApi;
import cn.itcast.tanhua.mytanhuaserver.service.BlacklistService;
import cn.itcast.tanhua.mytanhuaserver.service.QuanziService;
import cn.itcast.tanhua.mytanhuaserver.service.UserInfoService;
import cn.itcast.tanhua.mytanhuaserver.service.VideoService;
import cn.itcast.tanhua.pojo.FollowUser;
import cn.itcast.tanhua.pojo.User;
import cn.itcast.tanhua.pojo.UserInfo;
import cn.itcast.tanhua.pojo.Video;
import cn.itcast.tanhua.utils.UserThreadLocal;
import cn.itcast.tanhua.vo.PageInfo;
import cn.itcast.tanhua.vo.PageResult;
import cn.itcast.tanhua.vo.VideoVo;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.aliyunpicuploadspringbootstart.service.PicUploadService;
import com.itheima.aliyunpicuploadspringbootstart.vo.PicUploadResult;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * 关注用户
 * @author 郭文亮
 * @since 2021/12/1 18:32
 */
@Service
public class VideoServiceImpl implements VideoService {

    @Reference
    private VideoApi videoApi;

    @Reference
    private QuanziApi quanziApi;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private QuanziService quanziService;

    @Autowired
    private VideoMQService videoMQService;

    @Autowired
    private BlacklistService blacklistService;

    /**
     * 关注用户
     * @param followUserId 被关注人的id
     * @return 关注的结果
     * @throws Exception 可能出现的异常
     */
    @Override
    public Boolean userFocus(Long followUserId) throws Exception {
        // 创建结果集对象followUser
        FollowUser followUser = new FollowUser();

        // 通过UserThreadLocal获取当前用户信息
        User user = UserThreadLocal.get();

        // 将userId和followUserId封装到followUser
        followUser.setUserId(user.getId());
        followUser.setFollowUserId(followUserId);
        // 封装id和created
        followUser.setId(new ObjectId());
        followUser.setCreated(System.currentTimeMillis());

        // 调用api，存储followUser信息
        return this.videoApi.userFocus(followUser);
    }

    /**
     * 取消关注用户
     * @param followUserId 被取消关注人的id
     * @return 取消关注的结果
     * @throws Exception 可能出现的异常
     */
    @Override
    public Boolean userUnFocus(Long followUserId) throws Exception {
        // 创建结果集对象followUser
        FollowUser followUser = new FollowUser();

        // 通过UserThreadLocal获取当前用户信息
        User user = UserThreadLocal.get();

        // 将userId和followUserId封装到followUser
        followUser.setUserId(user.getId());
        followUser.setFollowUserId(followUserId);

        // 调用api，删除followUser信息
        return this.videoApi.userUnFocus(followUser);
    }

    @Override
    public Boolean saveVideo(MultipartFile picFile, MultipartFile videoFile) throws Exception{
        // 创建结果集对象video
        Video video = new Video();

        // 通过UserThreadLocal获取当前用户信息
        User user = UserThreadLocal.get();

        // 上传封面图片，获取图片地址
        PicUploadResult picUploadResult = this.picUploadService.upload(picFile);

        // 上传视频，获取视频地址
        StorePath storePath = this.fastFileStorageClient.uploadFile(videoFile.getInputStream()
                , videoFile.getSize()
                , StrUtil.subAfter(videoFile.getOriginalFilename(), '.', true)
                , null);

        // 将video信息封装到video
        video.setUserId(user.getId());
        video.setPicUrl(picUploadResult.getName());
        video.setVideoUrl(fdfsWebServer.getWebServerUrl()+storePath.getFullPath());
        video.setId(new ObjectId());
        video.setCreated(System.currentTimeMillis());

        // TODO: 2021/12/1 video其他信息的封装，private Integer seeType; // 谁可以看，1-公开，2-私密，3-部分可见，4-不给谁看
        //    private String text; //文字
        //    private List<Long> seeList; //部分可见的列表
        //    private List<Long> notSeeList; //不给谁看的列表
        //    private String longitude; //经度
        //    private String latitude; //纬度
        //    private String locationName; //位置名称

        // 调用api，封装vid到video，将video上传到MongoDB，
        //发送消息
        this.videoMQService.likeVideoMsg(video.getId().toHexString());
        return this.videoApi.saveVideo(video);
    }

    /**
     * 查询小视频
     * @param page
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Override
    public PageResult querySmallVideos(Integer page, Integer pageSize) throws Exception {
        // 创建结果集pageResult
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        // 通过UserThreadLocal获取当前用户信息
        User user = UserThreadLocal.get();

        //获取黑名单id
        List<Long> blacklist = blacklistService.queryBlacklistById(user.getId());

        // 调用api，获取小视频的信息，包括videoUrl，cover
        PageInfo<Video> pageInfo = this.videoApi.querySmallVideos(page, pageSize, user.getId(),blacklist);

        List<Video> records = pageInfo.getRecords();

        if(CollUtil.isEmpty(records)){
            return pageResult;
        }

        //查询用户信息
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoListByUserIds(userIds);

        List<VideoVo> videoVoList = new ArrayList<>();
        for (Video record : records) {
            VideoVo videoVo = new VideoVo();

            videoVo.setUserId(record.getUserId());
            videoVo.setCover(record.getPicUrl());
            videoVo.setVideoUrl(record.getVideoUrl());
            videoVo.setId(record.getId().toHexString());
            videoVo.setSignature("我就是我~"); //TODO 签名

            videoVo.setCommentCount(0); //TODO 评论数
            videoVo.setHasFocus(0); //TODO 是否关注
            videoVo.setHasLiked(0); //TODO 是否点赞（1是，0否）
            videoVo.setLikeCount(0);//TODO 点赞数

            //填充用户信息
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equals(videoVo.getUserId(), userInfo.getUserId())) {
                    videoVo.setNickname(userInfo.getNickName());
                    videoVo.setAvatar(userInfo.getLogo());
                    break;
                }
            }

            videoVoList.add(videoVo);
        }

        pageResult.setItems(videoVoList);
        return pageResult;
    }

    /**
     * 点赞
     *
     * @param videoId
     * @return
     */
    @Override
    public Long likeComment(String videoId) {
        User user = UserThreadLocal.get();
        Boolean result = this.quanziApi.likeComment(user.getId(), videoId);
        if (result) {
            //发送消息
            this.videoMQService.likeVideoMsg(videoId);
            return this.quanziApi.queryLikeCount(videoId);
        }
        return null;
    }

    /**
     * 取消点赞
     *
     * @param videoId
     * @return
     */
    @Override
    public Long disLikeComment(String videoId) {
        User user = UserThreadLocal.get();
        Boolean result = this.quanziApi.disLikeComment(user.getId(), videoId);
        if (result) {
            //发送消息
            this.videoMQService.disLikeVideoMsg(videoId);
            return this.quanziApi.queryLikeCount(videoId);
        }
        return null;
    }

    @Override
    public PageResult queryCommentList(String videoId, Integer page, Integer pageSize) {
        return this.quanziService.queryCommentList(videoId, page, pageSize);
    }

    @Override
    public Boolean saveComment(String videoId, String content) {
        Boolean result = this.quanziService.saveComments(videoId, content);

        if(result){
            //发送消息
            this.videoMQService.commentVideoMsg(videoId);
        }

        return result;
    }
}
